package services

import (
	"com.opennews.openplatform/web_api/domain"
	"com.opennews.openplatform/web_api/shared"
	"time"
)

type UserService interface {
	GetById(id string) shared.MapData
	GetByYearAndMonth(year int, month int) shared.MapData
	List() []shared.MapData
	Create(user shared.MapData) shared.MapData
	Delete(id string)
}

// Returns the instance of private member, userService, which implements UserService interface.
func NewUserService() UserService {
	return userService{}
}

func (this userService) GetById(id string) shared.MapData {
	// This is only example. That's why it calls this.List() which returns list of map.
	users := this.List()

	var matchedUser shared.MapData

	for i := range users {
		if users[i]["id"] == id {
			matchedUser = users[i]
		}
	}

	return matchedUser
}

func (this userService) GetByYearAndMonth(year int, month int) shared.MapData {
	return nil
}

func (this userService) List() []shared.MapData {
	birthday, _ := time.Parse(shared.LongDateTimeFormat, "1982-03-19 23:59:02")

	users := []domain.User{}
	users = append(users, domain.User{Id: "a1", Username: "User1", Password: "123", Level: 1, IsAdmin: true, Birthday: birthday})
	users = append(users, domain.User{Id: "a2", Username: "User2", Password: "123", Level: 2, IsAdmin: false, Birthday: birthday})
	users = append(users, domain.User{Id: "a3", Username: "User3", Password: "123", Level: 3, IsAdmin: false, Birthday: birthday})

	result := []shared.MapData{}

	for i := range users {
		result = append(result, this.toMap(users[i]))
	}

	return result
}

func (this userService) Create(jsonData shared.MapData) shared.MapData {
	return nil
}

func (this userService) Delete(id string) {

}

// Converts user model to map[string]interface{} with needed properties for api client.
func (this userService) toMap(user domain.User) shared.MapData {
	return shared.MapData{
		"id":       user.Id,
		"username": user.Username,
		"level":    user.Level,
		"isAdmin":  user.IsAdmin,
		"birthday": user.Birthday.Format(shared.LongDateFormat),
	}
}

// Container of userService functions.
type userService struct{}
